import {defineStore} from 'pinia';
import {login, logout, getUserInfo} from '@/api/system/auth';
import type {LoginUserVO} from "@/types/system/auth";

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: null as LoginUserVO | null,
    permissions: [] as string[]
  }),

  getters: {
    isLoggedIn: (state) => !!state.token,
    userId: (state) => state.userInfo?.id,
    username: (state) => state.userInfo?.username,
    nickname: (state) => state.userInfo?.nickname,
    avatar: (state) => state.userInfo?.avatar,
    hasPermission: (state) => (permission: string) => {
      return state.permissions.includes(permission);
    }
  },

  actions: {
    // 设置Token
    setToken(token: string) {
      this.token = token;
      localStorage.setItem('token', token);
    },

    // 清除Token
    clearToken() {
      this.token = '';
      localStorage.removeItem('token');
    },

    // 设置用户信息
    setUserInfo(userInfo: LoginUserVO) {
      this.userInfo = userInfo;
    },

    // 设置权限
    setPermissions(permissions: string[]) {
      this.permissions = permissions;
    },

    // 登录
    async login(username: string, password: string) {
      try {
        const res = await login(username, password);
        if (res.data) {
          this.setToken(res.data.token);
          this.setUserInfo(res.data.user)
          return true;
        }
        return false;
      } catch (error) {
        console.error('登录失败', error);
        return false;
      }
    },

    // 登出
    async logout() {
      try {
        if (this.token) {
          await logout();
        }
      } catch (error) {
        console.error('登出失败', error);
      } finally {
        this.clearToken();
        this.userInfo = null;
        this.permissions = [];
      }
    },

    // 获取用户信息
    async fetchUserInfo() {
      if (!this.token) return false;

      try {
        const res = await getUserInfo();
        if (res.data) {
          this.setUserInfo(res.data);
          // 假设权限信息从后端返回的用户信息中获取
          // 这里简单模拟一些权限
          this.setPermissions(['system:user:list', 'system:role:list', 'system:menu:list']);
          return true;
        }
        return false;
      } catch (error) {
        console.error('获取用户信息失败', error);
        return false;
      }
    }
  }
});
